package com.reus.core.util;

import lombok.NonNull;
import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * description:
 * copyright: Copyright (c) 2018-2021
 * company: iSysCore Tech. Co., Ltd.
 *
 * @author liuxq@isyscore.com
 * @version 1.0
 * @date 2021-09-28 10:59:57
 */
public interface DefaultDateTime {

    String getPattern();

    DateTimeFormatter getFormatter();

    /**
     * 获取系统当前时间并格式化
     */
    default String now() {
        return this.format(LocalDateTime.now());
    }

    /**
     * 字符串转为 java.util.Date
     */
    default Date parse(@NonNull String source) {
        try {
            return DateUtils.parseDate(source, getPattern());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 格式化 java.util.Date
     */
    default String format(Date datetime) {
        return this.format(datetime.toInstant().atZone(ZoneId.systemDefault()));
    }

    /**
     * 格式化 java8 的日期时间类
     */
    default String format(TemporalAccessor accessor) {
        return getFormatter().format(accessor);
    }

    /**
     * 字符串转为 {@link LocalDateTime}
     */
    default LocalDateTime parseLocalDateTime(CharSequence source) {
        return LocalDateTime.parse(source, getFormatter());
    }

    /**
     * 字符串转为 {@link LocalDate}
     */
    default LocalDate parseLocalDate(CharSequence source) {
        return LocalDate.parse(source, getFormatter());
    }

    /**
     * 字符串转为 {@link LocalTime}
     */
    default LocalTime parseLocalTime(CharSequence source) {
        return LocalTime.parse(source, getFormatter());
    }
}
